import 'dart:async';
import 'dart:io';

import 'package:aichat_flutter_wallet/module/module_wallet/provider/wallet_index_provider.dart';
import 'package:aichat_flutter_wallet/module/module_wallet_manage/widgets/delete_wallet.dart';
import 'package:aichat_flutter_wallet/module/module_create_wallet/pages/set_pass_page.dart';
import 'package:aichat_flutter_wallet/module_common/provider/user_settings_provider.dart';
import 'package:aichat_flutter_wallet/module_common/provider/wallet_info_provider.dart';
import 'package:aichat_flutter_wallet/module_common/router/routers.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/kai_bottom_tip_dialog.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';
import 'package:lib_util/utils/utils.dart';

import '../../../module_common/utils/auth.dart';
import '../../../module_common/widgets/header/page_header.dart';
import '../../../module_common/widgets/public_tip/public_tip.dart';
import '../widgets/set_wallet_name.dart';

class WalletPersonalCenterPage extends StatefulWidget {
  const WalletPersonalCenterPage({super.key});

  @override
  State<WalletPersonalCenterPage> createState() =>
      _WalletPersonalCenterPageState();
}

class _WalletPersonalCenterPageState extends State<WalletPersonalCenterPage> {
  int walletType = 1; //钱包状态： 1初始check 2检测中 3没问题 4有问题
  late WalletCheckStatus walletCheckStatusInstance;
  bool isLoading = false;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }
  @override
  void didChangeDependencies(){
    super.didChangeDependencies();
  }

  @override
  void dispose() {

    /// 取消路由订阅
    super.dispose();
  }

  //检测钱包完整性
  CheckWalletIntegrity() async {
    if (walletType == 3) {
      return;
    }
    if (isLoading) {
      return;
    }
    isLoading = true;
    if (walletType == 4) {
      DialogType? callBackStatus = await context
          .read<WalletIndexProvider>()
          .checkWalletStatus(
              walletCheckStatus: walletCheckStatusInstance,
              checkUpload:
                  context.read<WalletInfoNotifier>().wallet?.type == 3 &&
                      context
                              .read<WalletInfoNotifier>()
                              .wallet!
                              .key
                              .split(',')
                              .length !=
                          1);
      WalletCheck.showErrorDialog(
          callBackStatus: callBackStatus,
          callBack: () {
            walletType = 1;
          }).then((value) {
        isLoading = false;
      });
      return;
    }
    setState(() {
      walletType = 2;
    });
    Future.delayed(Duration(seconds: 2), () async {
      try {
        WalletCheckStatus walletCheckStatus = await WalletCheck()
            .checkWalletException(
                checkUpload:
                    context.read<WalletInfoNotifier>().wallet?.type == 3 &&
                        context
                                .read<WalletInfoNotifier>()
                                .wallet!
                                .key
                                .split(',')
                                .length !=
                            1);
        walletCheckStatusInstance = walletCheckStatus;
        bool allCheckPass = await WalletCheck()
            .checkWalletAllPass(walletCheckStatus: walletCheckStatus);
        if (allCheckPass) {
          if (mounted)
            setState(() {
              walletType = 3;
            });
        } else {
          if (mounted)
            setState(() {
              walletType = 4;
            });
        }
        isLoading = false;
      } catch (e) {
        isLoading = false;
      }
      // if (walletType != 1) return;
    });
  }

  //删除钱包
  deleteWallet() {
    Utils.showBottomSheetDialog(context, DeleteWallet());
  }

  Widget WalletTypeWidget(value) {
    if (value == '1')
      return Text('Check',
          style: TextStyle(
              color: Color.fromRGBO(190, 189, 202, 1),
              fontWeight: FontWeight.w400,
              fontSize: 14.sp,
              height: (20 / 14).w));
    else if (value == '2')
      return Row(
        children: [
          Container(
              width: 16.w,
              height: 16.w,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                color: Color.fromRGBO(106, 106, 106, 1),
              )),
          SizedBox(
            width: 5.w,
          ),
          Text('Detecting',
              style: TextStyle(
                  color: Color.fromRGBO(190, 189, 202, 1),
                  fontWeight: FontWeight.w400,
                  fontSize: 14.sp,
                  height: (20 / 14).w))
        ],
      );
    else if (value == '3')
      return Row(
        children: [
          Image.asset(
            'assets/images/wallet/ok.png',
            width: 16.w,
            height: 16.w,
          ),
          SizedBox(
            width: 5.w,
          ),
          Text('Okay',
              style: TextStyle(
                  color: AppColors.c_868391,
                  fontWeight: FontWeight.w400,
                  fontSize: 14.sp,
                  height: (20 / 14).w))
        ],
      );
    else
      return Row(
        children: [
          Image.asset(
            'assets/images/wallet/anomaly.png',
            width: 16.w,
            height: 16.w,
          ),
          SizedBox(
            width: 5.w,
          ),
          Text('Anomaly',
              style: TextStyle(
                  color: AppColors.c_868391,
                  fontWeight: FontWeight.w400,
                  fontSize: 14.sp,
                  height: (20 / 14).w))
        ],
      );
  }

  // 每项
  Widget WidgetCenterItem(
      {String label = '',
      bool? showStatus = null,
      String value = '',
      Function? onTap,
      int index = 1}) {
    return InkWell(
      onTap: () {
        onTap?.call();
      },
      child: Container(
        padding:
            EdgeInsets.only(right: 20.w, left: 20.w, top: 15.w, bottom: 15.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Text(
                  label,
                  style: TextStyle(
                      color: Color.fromRGBO(51, 51, 51, 1),
                      fontWeight: FontWeight.w400,
                      fontSize: 14.sp,
                      height: (20 / 14).w),
                ),
                SizedBox(
                  width: 8.w,
                ),
                Visibility(
                    visible: value == 'Settings',
                    child: Container(
                      width: 8.w,
                      height: 8.w,
                      decoration: BoxDecoration(
                        color: AppColors.c_F4654D,
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                      ),
                    ))
              ],
            ),
            Row(
              children: [
                Visibility(
                  visible: index != 3,
                  child: Text(value,
                      style: TextStyle(
                          color: value == 'Settings' || index == 0
                              ? AppColors.c_868391
                              : Color.fromRGBO(190, 189, 202, 1),
                          fontWeight: FontWeight.w400,
                          fontSize: 14.sp,
                          height: (20 / 14).w)),
                ),
                Visibility(
                  visible: index == 3,
                  child: WalletTypeWidget(value),
                ),
                SizedBox(
                  width: 5.w,
                ),
                PublicImage(
                  image: 'assets/images/common/more.png',
                  width: 12.w,
                  height: 12.w,
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  // 每项
  Widget WidgetSwitchItem(
      {String label = '',
      bool isCheck = false,
      String desc = '',
      void Function(bool)? callBack}) {
    return InkWell(
        child: Container(
            padding: EdgeInsets.only(
                right: 10.w, left: 20.w, top: 10.w, bottom: 15.w),
            child: Column(children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    label,
                    style: TextStyle(
                      color: Color.fromRGBO(51, 51, 51, 1),
                      fontWeight: FontWeight.w400,
                      fontSize: 14.sp,
                    ),
                  ),
                  Row(
                    children: [
                      Transform.scale(
                        scale: 0.7,
                        child: Switch(
                          trackOutlineWidth:
                              MaterialStateProperty.resolveWith((states) => 0),
                          trackOutlineColor:
                              MaterialStateProperty.resolveWith<Color>(
                                  (Set<MaterialState> states) {
                            if (states.contains(MaterialState.selected)) {
                              return Colors.transparent; // 选中状态下的颜色
                            }
                            return Colors.transparent; // 默认颜色
                          }),
                          materialTapTargetSize:
                              MaterialTapTargetSize.shrinkWrap,
                          activeColor: Colors.white,
                          activeTrackColor: Color.fromRGBO(246, 246, 246, 1),
                          trackColor: MaterialStateProperty.resolveWith<Color>(
                              (Set<MaterialState> states) {
                            if (states.contains(MaterialState.selected)) {
                              return Color.fromRGBO(
                                  134, 103, 254, 1); // 选中状态下的颜色
                            }
                            return Color.fromRGBO(246, 246, 246, 1); // 默认颜色
                          }),
                          inactiveTrackColor: Color.fromRGBO(246, 246, 246, 1),
                          thumbColor: MaterialStateProperty.resolveWith<Color>(
                              (Set<MaterialState> states) {
                            if (states.contains(MaterialState.selected)) {
                              return Colors.white; // 选中状态下的颜色
                            }
                            return Colors.white; // 默认颜色
                          }),
                          value: isCheck,
                          onChanged: callBack,
                        ),
                      )
                    ],
                  )
                ],
              ),
              Row(
                children: [
                  Expanded(
                      child: Text(
                    desc,
                    style: TextStyle(
                        color: AppColors.c_868391,
                        fontWeight: FontWeight.w400,
                        fontSize: 14.sp,
                        height: 16 / 12),
                  )),
                  SizedBox(
                    width: 40.w,
                  )
                ],
              )
            ])));
  }

  @override
  Widget build(BuildContext context) {
    String WalletName =
        context.watch<WalletInfoNotifier>().walletName.isNotEmpty
            ? context.watch<WalletInfoNotifier>().walletName
            : "Mpc Wallet A";
    // TODO: implement build
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: PageHeaderCom(
          title: "Wallet Management",
          showBottomBorder: false,
          definedGoBack: true,
          goBack: () {
            bool isLast = !Navigator.canPop(context);
            if(!isLast){
              Navigator.pop(context);
            }
            //这里的返回是销毁flutter页面
            // SystemNavigator.pop(); 这个方法iOS返回不了。所以直接用桥
            // NativeChannelBridge().closeFlutterPage(num: 0);
          },
        ),
        body: SingleChildScrollView(child: Consumer<WalletIndexProvider>(
          builder: (c, model, _) {
            if (!model.isSetWallet) {
              return FutureBuilder<WalletInfo?>(
                future: model.checkInitWalletStatus(),
                builder: (context, snapshot) {
                  return Column(
                    children: [
                      // 钱包密码
                      WidgetCenterItem(
                          label: 'Wallet Password',
                          value: context
                                  .watch<UserSettingsProvider>()
                                  .hasPassword()
                              ? 'Change'
                              : 'Settings',
                          onTap: () async {
                            bool isSetPass = await context
                                .read<UserSettingsProvider>()
                                .hasPassword();
                            Navigator.of(context).push(MaterialPageRoute(
                                builder: (context) => SetPassPage(
                                      type: isSetPass ? '3' : '4',
                                    )));
                          }),
                      // 生物识别
                      if (Platform.isIOS)
                        Visibility(
                          visible: context
                              .read<UserSettingsProvider>()
                              .hasPassword(),
                          child: WidgetSwitchItem(
                              label: 'Biometric Security',
                              desc:
                                  'Activate biometric validation for enhanced Kai wallet security',
                              isCheck: context
                                  .watch<UserSettingsProvider>()
                                  .isBiometricPay(),
                              callBack: (value) async {
                                bool isBiometricPay = context
                                    .read<UserSettingsProvider>()
                                    .isBiometricPay();
                                if (isBiometricPay != value && value == true) {
                                  bool pass =
                                      await Authentication().startLocalAuth(
                                          showPasswordError: false,
                                          callBackError: () {
                                            Toast.show(context,
                                                status: '0',
                                                position: Dpositon.top,
                                                message:
                                                    "Verification password error",
                                                duration: Duration(
                                                    milliseconds: 3000));
                                          });
                                  if (!pass) return;
                                }
                                context
                                    .read<UserSettingsProvider>()
                                    .updateBiometric(!isBiometricPay);
                              }),
                        )
                    ],
                  );
                },
              );
            }
            return Column(
              children: [
                // 钱包名称
                WidgetCenterItem(
                    label: 'Wallet Name',
                    value: WalletName,
                    index: 0,
                    onTap: () {
                      Utils.showBottomSheetDialog(
                          context,
                          SetWalletName(
                              text: context
                                  .read<WalletInfoNotifier>()
                                  .walletName));
                    }),
                // 钱包密码
                WidgetCenterItem(
                    index: 1,
                    label: 'Wallet Password',
                    value: context.watch<UserSettingsProvider>().hasPassword()
                        ? 'Change'
                        : 'Settings',
                    onTap: () async {
                      bool isSetPass = await context
                          .read<UserSettingsProvider>()
                          .hasPassword();
                      Navigator.of(context)
                          .push(MaterialPageRoute(
                              builder: (context) => SetPassPage(
                                    type: isSetPass ? '3' : '4',
                                  )))
                          .then((value) {
                        walletType = 1;
                      });
                    }),
                // 钱包完整性检测
                // WidgetCenterItem(
                //     label: 'Check Wallet Integrity',
                //     value: walletType.toString(),
                //     index: 3,
                //     onTap: CheckWalletIntegrity),
                //mpc安全管理
                WidgetCenterItem(
                    label: 'MPC Security Management',
                    value: '',
                    onTap: () {
                      var type =
                          context.read<WalletInfoNotifier>().wallet!.type;
                      //判断如果是观察钱包，
                      if (type == 3) {
                        Routes.navigateTo(context, Routes.walletMPCSecurity)
                            .then((value) {
                          walletType = 1;
                        });
                      }
                      if (type == 2) {
                        Routes.navigateTo(context, Routes.walletMPCRecast)
                            .then((value) {
                          walletType = 1;
                        });
                        ;
                      }
                    }),
                // 生物识别
                if (Platform.isIOS)
                  Visibility(
                    visible:
                        context.watch<UserSettingsProvider>().hasPassword(),
                    child: WidgetSwitchItem(
                        label: 'Biometric Security',
                        desc:
                            'Activate biometric validation for enhanced Kai wallet security',
                        isCheck: context
                            .watch<UserSettingsProvider>()
                            .isBiometricPay(),
                        callBack: (value) async {
                          bool isBiometricPay = context
                              .read<UserSettingsProvider>()
                              .isBiometricPay();
                          if (isBiometricPay != value && value == true) {
                            bool pass = await Authentication().startLocalAuth(
                                showPasswordError: false,
                                callBackError: () {
                                  Toast.show(context,
                                      status: '0',
                                      position: Dpositon.top,
                                      message: "Verification password error",
                                      duration: Duration(milliseconds: 3000));
                                });
                            if (!pass) return;
                          }
                          context
                              .read<UserSettingsProvider>()
                              .updateBiometric(!isBiometricPay);
                        }),
                  ),
                // 销毁钱包
                WidgetCenterItem(
                    label: 'Destroy Wallet', value: '', onTap: deleteWallet),
              ],
            );
          },
        )));
  }
}
